package com.hay.pay.support.ali;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.hay.pay.exception.PayException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author LiMouRen
 * @date 2024/1/29
 */
@Slf4j
@Data
public class AliPayRequest {


    private AlipayClient alipayClient;

    private final static String SERVER_URL = "https://openapi.alipay.com/gateway.do";

    private final static String JSON = "json";

    private final static String UTF8 = "utf-8";

    private final static String RSA2 = "RSA2";

    private final static String AES = "AES";

    private AliPayConfig aliPayConfig;

    public static AliPayRequest init(){
        return new AliPayRequest();
    }

    public AliPayRequest aliPayConfig(AliPayConfig aliPayConfig){
        this.aliPayConfig = aliPayConfig;
        return this;
    }

    public AliPayRequest build(){
        String appId = aliPayConfig.getAppId();
        String appPrivateKey = aliPayConfig.getAppPrivateKey();
        String alipayPublicKey = aliPayConfig.getAlipayPublicKey();
        String appAesKey = aliPayConfig.getAppAesKey();
        if (Objects.isNull(appAesKey) || appAesKey.length() == 0){
            this.alipayClient = new DefaultAlipayClient(SERVER_URL, appId, appPrivateKey, JSON, UTF8, alipayPublicKey, RSA2);
        } else {
            this.alipayClient = new DefaultAlipayClient(SERVER_URL, appId, appPrivateKey, JSON, UTF8, alipayPublicKey, RSA2, appAesKey, AES);
        }
        return this;
    }

    /**
     * 如果 proxyAppAuthToken 不为空, 则是代理请求
     */
    public <T extends AlipayResponse> T execute(AlipayRequest<T> request){
        String proxyAppAuthToken = aliPayConfig.getProxyAppAuthToken();
        T response = null;
        try {
            response = this.alipayClient.execute(request,null,proxyAppAuthToken);
        }catch (Exception e){
            log.error("支付宝支付请求异常：{}",e.getMessage(),e);
            throw new PayException(e.getMessage());
        }
        if (!response.isSuccess()){
            log.error("支付宝支付请求异常：{}",response.getSubMsg());
            throw new PayException(response.getSubMsg());
        }
        return response;
    }

    /**
     * 不走代理请求
     */
    public <T extends AlipayResponse> T skipProxyExecute(AlipayRequest<T> request){
        aliPayConfig.setProxyAppAuthToken(null);
        return execute(request);
    }


    /**
     * 回调响应
     * @param response 响应
     * @param notifySuccess 是否回调成功
     */
    public static void noticeResponse(HttpServletResponse response, boolean notifySuccess){
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String outStr = notifySuccess ? "success" : "fail";
        try {
            response.getWriter().println(outStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

